package com.zpark.wxshop.service.impl;

import com.alibaba.fastjson.JSON;
import com.zpark.wxshop.Vo.ProductVo;
import com.zpark.wxshop.entity.Product;
import com.zpark.wxshop.mapper.ProductMapper;
import com.zpark.wxshop.service.IProductService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author PJone
 * @since 2023-09-04
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {

    @Autowired
    private RestHighLevelClient client;

    //单个添加商品
    @Override
    public Product AddProduct(Product product) throws IOException {
        IndexRequest indexRequest = new IndexRequest("product");
        indexRequest.id(Integer.toString(product.getId()));
        indexRequest.source(JSON.toJSONString(product), XContentType.JSON);
        IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
        return product;
    }

    //修改商品信息
    @Override
    public Product UpdateProduct(Product product) throws IOException {
        UpdateRequest updateRequest = new UpdateRequest("product", String.valueOf(product.getId()));
        updateRequest.doc(JSON.toJSONString(product), XContentType.JSON);
        UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
        return product;
    }

    //根据商品名称进行模糊查询
    @Override
    public List<Product> FindByTitle(String title) throws IOException {
        SearchRequest searchRequest = new SearchRequest("product");

        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title").field("shopName");
        highlightBuilder.preTags("<font color='red'>");
        highlightBuilder.postTags("</font>");

        SearchSourceBuilder builder = new SearchSourceBuilder()
                .query(QueryBuilders.multiMatchQuery(title, "title", "shopName"))
                        .highlighter(highlightBuilder);

        searchRequest.source(builder);

        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = searchResponse.getHits();
        List<Product> productList = new ArrayList<>();
        for (SearchHit hit : hits.getHits()){
            productList.add(JSON.parseObject(hit.getSourceAsString(), Product.class));
        }
        return productList;
    }

    //根据id查询单个
    @Override
    public Map<String, Object> FindById(Integer id) throws IOException {
        GetRequest getRequest = new GetRequest("product");
        getRequest.id(String.valueOf(id));
        GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
        return getResponse.getSourceAsMap();
    }

    //查询商品信息
    @Override
    public List<ProductVo> FindProducts(String title, String shopName, Integer StartPrice, Integer EndPrice, Integer StartNum, Integer EndNum, Integer pageNum , Integer pageSize) throws IOException {

        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(QueryBuilders.matchAllQuery());
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        if (title == null && shopName == null){
            builder.query(QueryBuilders.matchAllQuery());
        }else if (title != null && shopName == null){
            boolQueryBuilder.must(QueryBuilders.matchQuery("title", title));
        }else if (title == null && shopName != null){
            boolQueryBuilder.must(QueryBuilders.matchQuery("shopName", shopName));
        }else {
            boolQueryBuilder.must(QueryBuilders.matchQuery("title", title));
            boolQueryBuilder.must(QueryBuilders.matchQuery("shopName", shopName));
        }
        boolQueryBuilder.must(QueryBuilders.rangeQuery("price").lte(EndPrice).gte(StartPrice));
        boolQueryBuilder.must(QueryBuilders.rangeQuery("num").lte(EndNum).gte(StartNum));
        builder.query(boolQueryBuilder).from(pageNum).size(pageSize).sort("id", SortOrder.ASC);


        SearchRequest searchRequest = new SearchRequest("product");
        searchRequest.source(builder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        List<ProductVo> productList = new ArrayList<>();
        for (SearchHit hit : searchResponse.getHits().getHits()){
            productList.add(JSON.parseObject(hit.getSourceAsString(), ProductVo.class));
        }
        return productList;
    }


}
